<template>
	<!-- 头像信息 -->
	<view class="user-model">
		<view class="avatar-box">
            <u-avatar  size="140rpx" v-if=" userStore.avatar == '' "></u-avatar>
            <u-avatar :src="checkAndFixUrl(userStore.avatar)" size="140rpx" v-else></u-avatar>
			<view class="info">
                <!-- 已登录 -->
                <template v-if="userStore.token">
                    <view class="nickname" v-if="userStore.is_auth_userinfo == 0" @tap="login">设置昵称</view>
                    <view class="nickname" v-else>{{ userStore.name }}</view>
                    <view class="mobile">{{ userStore.mobile }}</view>
                </template>
                <!-- 未登录 -->
                <template v-else>
                    <view class="nickname" @tap="login">登录/注册</view>
                </template>
			</view>
		</view>
		<view class="kf" @tap="showPhone = true">
			<u-image width="70rpx" height="54rpx" :src="getServerStatic('/static/images/a8.png')"></u-image>
		</view>
	</view>
	<view class="content">
		<!-- 邀请卡片 -->
		<view class="invite-box" @tap="goVip">
			<u-image width="100%" height="172rpx" :src="getServerStatic('/static/images/b1.png')"></u-image>
			<!-- <view class="invite-info">
				<view class="invite-title">
					<view class="h1">邀请有礼</view>
					<view class="h2">邀请好友登录注册享好礼</view>
				</view>
				<view>
					<u-button throttleTime="1000" :customStyle="{height: '72rpx', letterSpacing: '.1rem'}" :hairline="false" type="mini"
						shape="circle" color="linear-gradient(147deg, rgba(255,255,255,0.4) 0%, #FFFFFF 100%)"
						@click="goInvite">
						<text style="color: #D66A44;">立即邀请</text>
					</u-button>
				</view>
			</view> -->
		</view>
		<!-- 跳转区 -->
		<view class="navigate-box">
			<u-grid :border="false" col="4" @click="navigateHandle">
				<u-grid-item v-for="(item, i) in navigateList" :key="i">
					<view class="item">
						<u-image width="64rpx" height="64rpx" :src="getServerStatic(item.icon)"></u-image>
						<view>{{item.name}}</view>
					</view>
				</u-grid-item>
			</u-grid>
		</view>
		<!--  -->
		<view class="cell-group">
			<view class="cell-item" @tap="goVisitor">
				<view class="left">
					<u-image width="84rpx" height="84rpx" :src="getServerStatic('/static/images/a43.png')"></u-image>
					<view>就诊人管理</view>
				</view>
				<u-icon name="arrow-right" color="#91959E" size="18"></u-icon>
			</view>
			<view class="cell-item" @tap="goAdress">
				<view class="left">
					<u-image width="84rpx" height="84rpx" :src="getServerStatic('/static/images/a13.png')"></u-image>
					<view>地址管理</view>
				</view>
				<u-icon name="arrow-right" color="#91959E" size="18"></u-icon>
			</view>

			<view class="cell-item" @tap="goInvite">
				<view class="left">
					<u-image width="84rpx" height="84rpx" :src="getServerStatic('/static/images/a14.png')"></u-image>
					<view>推广有礼</view>
				</view>
				<u-icon name="arrow-right" color="#91959E" size="18"></u-icon>
			</view>
			<view class="cell-item" @tap="goAboutUs">
				<view class="left">
					<u-image width="84rpx" height="84rpx" :src="getServerStatic('/static/images/a16.png')"></u-image>
					<view>关于我们</view>
				</view>
				<u-icon name="arrow-right" color="#91959E" size="18"></u-icon>
			</view>
		</view>
	</view>

	<!-- 客服电话 -->
	<u-action-sheet round="30rpx" :show="showPhone" :actions="actions" title="" description=""
		@close="showPhone = false" @select="callConfirm">
	</u-action-sheet>

	<!-- 上传头像和昵称 -->
	<u-popup :show="userPop" @close="userPop = false" mode="center" closeOnClickOverlay bgColor="transparent">
		<view class="user-pop">
			<view class="avatar-upload">
<!--				<view class="">-->
<!--					<u-upload :fileList="fileList" @afterRead="avatarUpload" @delete="deletePic" name="6" :maxCount="1"-->
<!--						width="170rpx" height="170rpx">-->
<!--						<u-image shape="circle" width="170rpx" height="170rpx" src="/static/images/avatar.png"></u-image>-->
<!--					</u-upload>-->
<!--				</view>-->
                <view>
                    <button class="avatar-button" open-type="chooseAvatar" @chooseavatar="onChooseAvatar">
                        <image :class="avatar == '' ? 'avatar-img' : '' " :src="avatarUrl"></image>
                    </button>
                </view>
			</view>
            <view class="nickname-box">
                <input type="nickname" class="weui-input" placeholder="请输入昵称" border="none" @change="handleChangeNickname" v-model="nickname" inputAlign="center" />
            </view>
            <view class="confirm">
                <u-button :disabled="isDisabled" plain color="transparent" :hairline="false" class="custom-style" @click="editUserConfirm">
                    <text style="color: #516DDB;font-size: 36rpx;">确认授权</text>
                </u-button>
            </view>
		</view>
	</u-popup>
	<!-- tabbar -->
	<TabBar :current-page="2"></TabBar>
</template>

<script setup>
    import {ref, reactive, readonly} from 'vue'
    import {onLoad, onShow, onReady} from '@dcloudio/uni-app'
    import { useUserStore, useSystemStore } from '@/store';
	import TabBar from "@/components/Tabbar"
    import {getUploadToken, uploadImage} from "@/api/upload";
    import {authAvatarNickname} from "@/api/user";
    import {checkAndFixUrl, getServerStatic} from "@/utils/tool";

    // 用户store
    const userStore = useUserStore();
    const systemStore = useSystemStore()

    // 上传头像 昵称
    const avatarUrl = ref('')
    const avatar = ref('')
    const userPop = ref(false)
    const fileList = ref([])
    const nickname = ref('')
    const deletePic = () => {
        fileList.value = []
    }
    const avatarUpload = (event) => {
        console.log(event.file);
        fileList.value = [event.file]
    }
    const isDisabled = computed(() => {
        // return !nickname.value || (fileList.value.length == 0)
        let isDisabled = false
        if (avatar.value == '') {
            isDisabled = true
        }
        if (nickname.value == '') {
            isDisabled = true
        }
        return isDisabled
    })

    // 确认授权.
    const editUserConfirm = async () => {
        const {code, data, message} = await authAvatarNickname({nickname: nickname.value, avatar: avatar.value})

        if (code == 1) {
            userStore.syncUserInfo()
            userPop.value = false
        }
    }

    // 微信登录
    const login = () => {
        // 如果没登录
        if (!userStore.token) {
            const pages = getCurrentPages()
            let fromPath = "/" + pages[pages.length - 1].route
            // @ts-ignore
            uni.navigateTo({
                url: "/pages/login/login?fromPath=" + encodeURIComponent(fromPath)
            });
        } else {
            // 如果已登录
            nickname.value = ''
            fileList.value = []
            userPop.value = true
        }
    }

    // 选择头像
    const onChooseAvatar = async (e) => {
        const {code, data, message} = await getUploadToken()
        if (code !== 1) {
            uni.showModal({
                title: '提示',
                content: message ?? "获取上传token异常",
                showCancel: false,
                success: function (res) {
                }
            });
            return
        }
        console.log('获得头像', e)
        const uploadRes = await uploadImage({file: e.detail.avatarUrl}, data.token)
        const uploadResData = JSON.parse(uploadRes)
        console.log('上传后', uploadResData)
        if (uploadResData.code != 1) {
            console.log('上传异常', message)
            return
        }
        avatar.value = uploadResData.data.path
        avatarUrl.value = uploadResData.data.url
    }

    const handleChangeNickname = (e) => {
        if (e.detail.value) {
            console.log(e)
            nickname.value = e.detail.value
        }
    }

	const navigateList = readonly([{
			name: '电子病历',
			href: '/mine/medical/list',
            needLogin: true,
			icon: '/static/images/a9.png'
		},
		{
			name: '挂号订单',
			href: '/mine/order/list',
            needLogin: true,
			icon: '/static/images/a10.png'
		},
		{
			name: '商品订单',
			href: '/mine/commodity/list',
            needLogin: true,
			icon: '/static/images/a11.png'
		},
		{
			name: '我的礼包',
			href: '/mine/gift/gift',
            needLogin: true,
			icon: '/static/images/a12.png'
		}
	])

    const navigateHandle = (e) => {
        let href = navigateList[e].href
        let needLogin = navigateList[e].needLogin
        if (needLogin && !userStore.token) {
            toLogin()
        } else {
            uni.navigateTo({
                url: href
            })
        }
    }

    const toLogin = () => {
        uni.showToast({
            mask: true,
            title: '请先登录!',
            icon: 'error'
        })
        const pages = getCurrentPages()
        let fromPath = "/" + pages[pages.length - 1].route
        setTimeout(() => {
            // @ts-ignore
            uni.redirectTo({
                url: "/pages/login/login?fromPath=" + encodeURIComponent(fromPath)
            });
        },800)
    }

    // 客服
    const showPhone = ref(false)
    const actions = ref([{
        name: `一键拨打：${systemStore.customer}`,
        isCall: true
    },
        {
            name: '取消',
            isCall: false
        },
    ])
    // 拨打电话
    const callConfirm = e => {
        console.log(e);
        if (e.isCall) {
            uni.makePhoneCall({
                phoneNumber: systemStore.customer
            })
        }
    }

	// 关于我们
	const goAboutUs = () => {
		uni.navigateTo({
			url: `/mine/about-us/about-us`
		})
	}
	// 就诊人管理
	const goVisitor = () => {
		uni.navigateTo({
			url: `/mine/visitor/list`
		})
	}
	// 地址管理
	const goAdress = () => {
		uni.navigateTo({
			url: `/mine/address/list`
		})
	}
	// 推广
	const goInvite = () => {
		uni.navigateTo({
			url: '/mine/invite/invite'
		})
	}
	// 会员充值
	const goVip = () => {
		uni.navigateTo({
			url: '/mine/vip/vip'
		})
	}
</script>

<style lang="scss" scoped>
	.user-pop {
		background: #FFFFFF;
		border-radius: 16rpx;
		@include center(560rpx);
		flex-direction: column;

        .avatar-button {
            width: 150rpx;
            padding: 0;
            border-radius: 50%;
            margin: 30rpx auto 0 auto;

            image {
                width: 150rpx;
                height: 150rpx;
                border-radius: 50%;
                display: block;
                //border: 4rpx solid #d8bf9f;
            }
        }

        .avatar-img {
            z-index: 3;
            position: relative;

            &:before {
                content: '点击授权';
                position: absolute;
                top: 0;
                left: 0;
                width: 150rpx;
                height: 150rpx;
                // line-height: 40rpx;
                display: flex;
                align-items: center;
                justify-content: center;
                color: #ffffff;
                font-size: 25rpx;
                background-color: rgba(130, 128, 127, 0.5);
                z-index: 4;
            }
        }

        .avatar-upload {
            @include center(100%);
            padding: 52rpx 0;
            border-bottom: 1rpx solid #E5E5E5;
        }

        .nickname-box {
            display: flex;
            align-items: center;
            width: 100%;
            padding: 40rpx;
            border-bottom: 1rpx solid #E5E5E5;

            .weui-input {
                flex: 1;
                color: #333;
                font-size: 30rpx;
                text-align: center;
            }
        }
        .confirm {
            width: 100%;
            padding: 40rpx 0;
        }

		.confirm {
			width: 100%;
			padding: 40rpx 0;
		}
	}

	.user-model {
		@include between(100%);
		padding: 40rpx 38rpx 120rpx;
		background: #FFFFFF;

		.avatar-box {
			@include start();

			.info {
				margin-left: 28rpx;
				color: #222222;

				.nickname {
					font-size: 36rpx;
				}

				.mobile {
					font-size: 30rpx;
					margin-top: 8rpx;
				}
			}
		}
	}

	.content {
		padding: 0 38rpx 200rpx;
		margin-top: -80rpx;
	}

	.invite-box {
		position: relative;
		width: 100%;
		height: 172rpx;

		.invite-info {
			position: absolute;
			left: 0;
			top: 0;
			@include between(100%, 100%);
			z-index: 9;
			padding: 32rpx 40rpx;

			.invite-title {
				color: #FFFFFF;

				.h1 {
					font-size: 48rpx;
				}

				.h2 {
					margin-top: 4rpx;
				}
			}
		}
	}

	.navigate-box {
		margin-top: 40rpx;
		background: #FFFFFF;
		border-radius: 30rpx;
		padding: 50rpx 10rpx;

		.item {
			@include center();
			flex-direction: column;
			color: #606672;
			font-size: 30rpx;

			&>view {
				margin-top: 24rpx;
			}
		}
	}

	.cell-group {
		margin-top: 40rpx;

		.cell-item {
			@include between(100%, 130rpx);
			background: #FFFFFF;
			border-radius: 30rpx;
			padding: 0 30rpx;
			margin-bottom: 30rpx;

			.left {
				@include start();

				&>view {
					font-size: 32rpx;
					color: #606672;
					margin-left: 32rpx;
				}
			}
		}
	}
</style>
